package com.sudo.service.admin.service.impl;

import com.sudo.common.utils.JsonUtil;
import com.sudo.dao.admin.entity.SysInfo;
import com.sudo.dao.admin.mapper.SysInfoMapper;
import com.sudo.dao.admin.model.vo.SysMemCpuVO;
import com.sudo.service.admin.service.AdminBaseService;
import com.sudo.service.admin.service.SysInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 为道日损 2020-07-07 11:12
 * webSite：https://www.sudo.ren
 */
@Service
public class SysInfoServiceImpl extends AdminBaseService implements SysInfoService {

    @Resource
    private SysInfoMapper sysInfoMapper;


    @Transactional(propagation = Propagation.SUPPORTS,rollbackFor = Exception.class)
    @Override
    public List<SysInfo> getSysInfoByServer(String serverNode) {
        Example example = new Example(SysInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("server", serverNode);
        return sysInfoMapper.selectByExample(example);
    }

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public int deleteSysInfoByServer(String serverNode){
        Example example = new Example(SysInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("server", serverNode);
        return sysInfoMapper.deleteByExample(example);
    }

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public int insertSysInfoByBatch(String serverNode, Map<String, Object> map) {
        List<SysInfo> sysInfoList = new ArrayList<>();
        map.forEach((k,v)->{
            SysInfo sysInfo = new SysInfo(k,serverNode,v.toString());
            sysInfoList.add(sysInfo);
        });
        return sysInfoMapper.insertList(sysInfoList);
    }

    @Override
    public void insertMemCpuToRedis(String server, SysMemCpuVO sysMemCpuVO) {
        String data = JsonUtil.objectToJson(sysMemCpuVO);
        setSysCpuMemInfoByRealTime(redisKeys.getMemCpuRedisRealTimeKey(server),data);
    }

    @Override
    public List<SysInfo> getSysInfoByCode(String...code){
        Example example = new Example(SysInfo.class);
        Example.Criteria criteria = example.createCriteria();
        for (String s : code) {
            criteria.orEqualTo("code",s);
        }
        return sysInfoMapper.selectByExample(example);
    }

}
